// pages/dynamics.js
import {
  get_carte,
  get_open_id,
  user_login,
  update_coll_status,
  update_like_status,
  update_flag_like_status,
  baseUrl
} from "../../utils/api.js"; 

const app = getApp()
var page = 1;
var selectedNews = false;
var newsList = [];
const util = require('../../utils/util')
const {
  formatTimeC
} = util


Page({

  /**
   * 页面的初始数据
   */
  data: {
    u_id: "",
    v_id: "",
    plTask:false,
    userPic: "",
    cardLogo: "",
    cardUsername: "",
    shareInfo: [],
    isDianzan: "",
    inputBoxShow: false, 
    isScroll: true,
    commContent: "",
    commId: "",
    commIndex: "",
    TaskShow: 0,
    phoneShow: 0,
  },
  // 点击更多进去公司视频
  bindComVideos: function (e) {
    wx.navigateTo({
      url: '../companyVideos/companyVideos',
    })
  },
  // 点击评论弹出点赞评论
  showTask: function (e) {
    this.getUserDianzan(e.currentTarget.dataset.id);
    for(var i=0;i<this.data.shareInfo.length;i++){
      if (e.currentTarget.dataset.id == this.data.shareInfo[i].dynamic.id){
        this.data.shareInfo[i].dynamic.plTask = !this.data.shareInfo[i].dynamic.plTask;
      }
    }
    this.setData({
      shareInfo: this.data.shareInfo
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.vid) {
      app.globalData.SwitchTabParams.v_id = options.vid;
    }
  },

  //获取用户的封面图
  getUserPic: function (img_id) {
    const that = this
    let url2 = '/dynamics_api/backGround';
    let params = {
      uid: app.globalData.SwitchTabParams.v_id,
      img_id: img_id
    };
    app.HttpGetSend(url2, params, function (res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        that.setData({
          userPic: res.data.url
        })
      }
    })
  },

  //获取用户的动态列表数据
  getDynamicsList: function(){
    const that = this
    let url2 = '/dynamics_api/dynamicsList';
    let params = {
      uid: app.globalData.SwitchTabParams.v_id,
      pageNo: page,
      pagesize: 10
    };
    app.HttpGetSend(url2, params, function (res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
        selectedNews = false;
        that.setData({
          shareInfo: []
        })
      } else {
        var shareInfo = res.data;
        const timestamp = parseInt(new Date().getTime() / 1000)
        for (var i = 0; i < shareInfo.length; i++) {
          
          let aim_timestamp = parseInt(new Date(shareInfo[i].dynamic.create_time * 1000).getTime() / 1000)
          shareInfo[i].dynamic.create_time = formatTimeC(timestamp, aim_timestamp)

          shareInfo[i].dynamic.plTask = false;
          that.getUserDianzan(shareInfo[i].dynamic.id);
          for (var j = 0; j < shareInfo[i].comments.length;j++){
            shareInfo[i].comments[j].weixin = shareInfo[i].comments[j].weixin+" : ";
          }
          newsList.push(shareInfo[i]);
        }
        if (shareInfo.length < 10) {
          selectedNews = false;
        } else {
          selectedNews = true;
          page += 1;
        }
        
        that.setData({
          shareInfo:newsList
        })
        wx.hideLoading();
      }
    })
  },

  //获取动态的点赞状态
  getUserDianzan: function (d_id) {
    const that = this
    let url2 = '/dynamics_api/getDynamicPoint';
    let params = {
      uid: app.globalData.userInfo.id,
      d_id: d_id
    };
    app.HttpPostSend(url2, params, function (res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        for (var i = 0; i < that.data.shareInfo.length; i++) {
          if (d_id == that.data.shareInfo[i].dynamic.id) {
            that.data.shareInfo[i].dynamic.isDianzan = res.data.status;
          }
        }
        that.setData({
          shareInfo: that.data.shareInfo
        })
      }
    })
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  // 检测是否需要登录
  checkUserInfo: function () {
    const that = this
    let openid = wx.getStorageSync('openid')
    if (openid) {
      app.globalData.openid = openid
      that.setData({
        openid,
      })
      let url = '/user_api/getInfoByOpenID';
      app.HttpPostSend(
        url, {
          openid: openid,
        },
        function (result_data) {
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            if (!!result_data.data) {//如果后台有数据
              app.globalData.userInfo = {
                ...result_data.data
              }
              wx.setStorage({
                key: 'userInfo',
                data: JSON.stringify({
                  ...result_data.data
                })
              })
              that.setData({
                userInfo: result_data.data
              })

              that.getDynamicsList();
              that.getUserPic('');

              try {
                // ai添加纪录 对我感兴趣
                app.aiAddRecord(1)
              } catch (error) {
                console.log(error)
              }

              if (app.globalData.userInfo.id != app.globalData.SwitchTabParams.v_id) {

                // 雷达添加查看记录 -动态访问数
                app.radarAdd(app.globalData.SwitchTabParams.v_id, 8, '', '', app.globalData.userInfo.logo)

                // 发送模板消息-访客到访通知
                // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter', '正在访问动态', '', '', '')
              }

              that.setData({
                userInfo: app.globalData.userInfo,
                u_id: Number(app.globalData.userInfo.id),
                v_id: Number(app.globalData.SwitchTabParams.v_id)
              })

              let url2 = '/dynamics_api/userLogo';
              let params = {
                uid: app.globalData.SwitchTabParams.v_id
              };
              app.HttpPostSend(url2, params, function (res) {
                if (res.msg != "success") {
                  app.showTipMsg(res.msg);
                } else {
                  that.setData({
                    cardLogo: res.data.logo,
                    cardUsername: res.data.username,
                  })
                }
              })

            } else {//如果后台无数据
              wx.login({
                success(res) {
                  let params = {
                    code: res.code
                  }
                  app.HttpGetSend(get_open_id, params, function (result) {
                    if (result.msg != "success") {
                      app.showTipMsg(result.msg);
                    } else {
                      app.globalData.openid = result.data.openid.openid;
                      wx.setStorage({
                        key: 'openid',
                        data: result.data.openid.openid
                      })
                      that.setData({
                        openid: result.data.openid.openid
                      })
                      that.setData({
                        TaskShow: 1,
                        openid: result.data.openid.openid
                      })
                    }
                  })
                }
              })
            }
          }
        })
    } else {
      wx.login({
        success(res) {
          let params = {
            code: res.code
          }
          app.HttpGetSend(get_open_id, params, function (result) {
            if (result.msg != "success") {
              app.showTipMsg(result.msg);
            } else {
              app.globalData.openid = result.data.openid.openid;
              wx.setStorage({
                key: 'openid',
                data: result.data.openid.openid
              })
              that.setData({
                openid: result.data.openid.openid
              })
              that.setData({
                TaskShow: 1,
                openid: result.data.openid.openid
              })
            }
          })
        }
      })
    }
  },

  // 获取用户信息
  bindGetUserInfo: function (e) {
    const that = this
    let userInfo = e.detail.userInfo
    try {
      app.HttpPostSend(
        user_login, {
          openid: that.data.openid,
          username: userInfo.nickName,
          logo: userInfo.avatarUrl,
          sex: userInfo.gender
        },
        function (result_data) {
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            let userInfo = {
              ...result_data.data
            }
            app.globalData.userInfo = userInfo
            wx.setStorage({
              key: 'userInfo',
              data: JSON.stringify(userInfo)
            })
            that.setData({
              TaskShow: 0,
              userInfo: userInfo
            })

            that.getDynamicsList();
            that.getUserPic('');

            try {
              // ai添加纪录 对我感兴趣
              app.aiAddRecord(1)
            } catch (error) {
              console.log(error)
            }

            if (app.globalData.userInfo.id != app.globalData.SwitchTabParams.v_id) {

              // 雷达添加查看记录 -动态访问数
              app.radarAdd(app.globalData.SwitchTabParams.v_id, 8, '', '', app.globalData.userInfo.logo)

              // 发送模板消息-访客到访通知
              // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter', '正在访问动态', '', '', '')
            }

            that.setData({
              userInfo: app.globalData.userInfo,
              u_id: Number(app.globalData.userInfo.id),
              v_id: Number(app.globalData.SwitchTabParams.v_id)
            })

            let url2 = '/dynamics_api/userLogo';
            let params = {
              uid: app.globalData.SwitchTabParams.v_id
            };
            app.HttpPostSend(url2, params, function (res) {
              if (res.msg != "success") {
                app.showTipMsg(res.msg);
              } else {
                that.setData({
                  cardLogo: res.data.logo,
                  cardUsername: res.data.username,
                })
              }
            })
          }
        })
    } catch (error) {

    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    page = 1;
    selectedNews = false;
    newsList = [];
    this.setData({
      shareInfo:[]
    })
    this.checkUserInfo();
  },

  // 点赞/取消点赞
  bindDianzan: function (e) {
    var d_id = e.currentTarget.dataset.id;
    var status = e.currentTarget.dataset.status;
    var shareindex = e.currentTarget.dataset.shareindex;
    if (status != 0) {

      if (app.globalData.userInfo.id != app.globalData.SwitchTabParams.v_id) {
        // 雷达添加查看记录 -点赞了动态数
        app.radarAdd(app.globalData.SwitchTabParams.v_id, 21, '', '', app.globalData.userInfo.logo)

        // 发送模板消息-作品被点赞通知
        // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 5, '/radarPages/radarCenter/radarCenter', '您的名片被点赞', '', '', '')
      }
    }
    
    const that = this
    let url = '/dynamics_api/updateDynamicPoint';
    let params = {
      d_id: d_id,
      uid: app.globalData.userInfo.id,
      status: status
    };
    app.HttpPostSend(url, params, function (res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        that.data.shareInfo[shareindex].dynamic.plTask = !that.data.shareInfo[shareindex].dynamic.plTask;
        that.data.shareInfo[shareindex].point = res.data;
        that.setData({
          shareInfo: that.data.shareInfo
        })
      }
    })
  },

  //删除一条动态
  bindDelete: function (e) {
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    const that = this
    let url = '/dynamics_api/delDynamic';
    let params = {
      id: id
    };
    app.HttpPostSend(url, params, function (res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        that.data.shareInfo.splice(index, 1);
        that.setData({
          shareInfo: that.data.shareInfo
        })
      }
    })
  },

  //发布一则动态信息
  updateInfo:function(e){
    wx.navigateTo({
      url: '/pages/releaseDynamic/releaseDynamic'
    })
  },

  // 打开个人统计信息页
  showPerson: function () {
    wx.switchTab({
      url: '/pages/person/person',
    })
  },
  
  // wx.makePhoneCall({
  makeCall: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.content// 仅为示例，并非真实的电话号码
    })
  },

  previewImg(e) {
    let shareInfoindex = e.currentTarget.dataset.shareinfoindex;
    let index = e.currentTarget.dataset.index;
    var imgurl = this.data.shareInfo[shareInfoindex].imgs;
    var urls = [];
    for (var i = 0; i < imgurl.length; i++) {
      urls.push(imgurl[i].url);
    }
    wx.previewImage({
      current: imgurl[index].url,
      urls: urls,
    })
  },

  chooseimage: function () {
    if(this.data.u_id == this.data.v_id){
      var that = this;
      wx.chooseImage({
        count: 1, // 默认9  
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有 
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
        success: function (res) {
          var url = '/dynamics_api/dynaUploadsImg';
          wx.uploadFile({
            url: baseUrl + url, // 仅为示例，非真实的接口地址
            filePath: res.tempFilePaths[0],
            name: 'file',
            formData: {},
            success(resp) {
              let json_res = JSON.parse(resp.data)
              if (json_res.msg != "success") {
                app.showTipMsg(json_res.msg);
              } else {
                that.getUserPic(json_res.data);
              }
            },
            fail(err) {
              console.log(err)
            }
          })

        }
      })
    }
  },

  bindPinglun: function (e) {
    var commIndex = e.currentTarget.dataset.shareindex;
    this.data.shareInfo[commIndex].dynamic.plTask = !this.data.shareInfo[commIndex].dynamic.plTask;
    this.setData({
      commId: e.currentTarget.dataset.id,
      commIndex: commIndex,
      inputBoxShow: true,
      isScroll: false,
      shareInfo: this.data.shareInfo
    })
  },

  invisible: function () {
    this.setData({ 
      inputBoxShow: false,
      isScroll: true
    });
  },

  //输入评论
  inputComm: function (e) {
    this.setData({
      commContent: e.detail.value
    })
  },

  //发表评论
  sendComm: function (e) {
    if (this.data.commContent == ''){
      app.showTipMsg('请输入内容');
      return false;
    }
    let that = this;
    var url = '/dynamics_api/addDynamic';
    var params = {
      uid: app.globalData.userInfo.id,
      title: that.data.commContent,
      pid: that.data.commId,
      type: 1
    };
    app.HttpPostSend(url, params, function (res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        wx.showModal({
          title: '评论成功',
          showCancel: false,
          success: function (resp) {
            if (resp.confirm) {
              that.invisible();
              // that.getDynamicsList();
              that.data.shareInfo[that.data.commIndex].comments = res.data.list;
              that.setData({
                shareInfo: that.data.shareInfo
              })
            }
          }
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (selectedNews == true) {
      var that = this;
      // 显示加载图标  
      wx.showLoading({
        title: '玩命加载中',
      })
      // 页数+1  
      this.getDynamicsList();

    } else {
      wx.hideLoading();
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    const that = this

    return {
      title: '我在尽猎科技发现尽猎AI门店帮扶系统，赶快来看看吧',
      path: '/pages/dynamics/dynamics?vid=' + app.globalData.SwitchTabParams.v_id,
      imageUrl: '',
      complete(res) {
      }
    }
  }
})